package com.monkeyboy.mytest.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageRowBounds;
import com.monkeyboy.mytest.common.ParamData;

@Repository("Dao")
@Transactional
public class BaseDao{
	@Autowired
	private SqlSessionTemplate sqlSessionTemplate;
	/**
	 * <p>描述:保存</p>
	 * @return	返回改变的行数
	 */
	public int save(String str, Object obj) throws Exception {
		Object o = sqlSessionTemplate.insert(str, obj);
		return Integer.parseInt(o.toString());
	}
	/**
	 * <p>描述:更新</p>
	 * @return	返回改变的行数
	 */
	public int update(String str, Object obj) throws Exception {
		Object o = sqlSessionTemplate.update(str, obj);
		return Integer.parseInt(o.toString());
	}
	/**
	 * <p>描述:删除</p>
	 * @return	返回改变的行数
	 */
	public int delete(String str, Object obj) throws Exception {
		Object o = sqlSessionTemplate.delete(str, obj);
		return Integer.parseInt(o.toString());
	}
	/**
	 * <p>描述: 查询一个值.比如查行数 count(*)	的结果</p>
	 * @return	返回改变的行数
	 */
	public int findForNum(String str, Object obj) throws Exception {
		String s = sqlSessionTemplate.selectOne(str, obj).toString();
		return Integer.parseInt(s.substring(s.indexOf("=") + 1, s.length() - 1));
	}
	/**
	 * <p>描述:查询单个结果</p>
	 * @return	返回改变的行数
	 */
	public Object findForObject(String str, Object obj) throws Exception {
		return sqlSessionTemplate.selectOne(str, obj);
	}
	/**
	 * <p>描述:查询多个结果</p>
	 * @return	返回改变的行数
	 */
	public Object findForList(String str, Object obj) throws Exception {
		return sqlSessionTemplate.selectList(str, obj);
	}
	
	/**
	 * pagehelper装配
	 * @author Gavin
	 */
	public Object findForPaging(String str, ParamData pd) throws Exception {
		// 取出当前页数,没取到为第一页
		Integer page = new Integer(pd.get("page") == null ? "0" : String.valueOf(pd.get("page")));
		Integer limit = new Integer(pd.getString("limit") == null ? "0" : String.valueOf(pd.get("limit")));
		if (page < 1) {
			page = 1;
		}
		// 计算页开始位置
		int index = (page - 1) * limit;
		PageRowBounds pageRowBounds = new PageRowBounds(index, limit);
		List<Map<String, Object>> list = sqlSessionTemplate.selectList(str, pd, pageRowBounds);
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("data", list);
		//获取总数据量
		data.put("count",String.valueOf(pageRowBounds.getTotal()));
		return data;
	}

}
